#!/bin/bash
###
# @Author: Logan.Li
# @Date: 2025-09-09 00:32:00
# @LastEditTime: 2025-09-09 00:32:00
# @Description: Jenkins多JDK版本管理脚本 - 支持Jenkins启动使用JDK17，Job使用JDK11
# @支持系统: RHEL/CentOS/Rocky/AlmaLinux/Amazon Linux 2/Amazon Linux 2023/Debian/Ubuntu
###
# curl -s https://gitee.com/attacker/All-In-One-Ops/raw/master/1.scripts/services/jenkins-jdk-manager.sh | bash

# 基础设置
set -e  # 遇到错误立即退出

# 路径定义
DOWNLOAD_DIR="/usr/local/src"
INSTALL_DIR="/opt"
JDK11_DIR="/data/jdk-11"
JDK17_DIR="/data/jdk-17"
JENKINS_HOME="/var/lib/jenkins"

# 简洁输出函数
info() { echo -e "\e[34m[INFO]\e[0m $1"; }
warn() { echo -e "\e[33m[WARN]\e[0m $1"; }
error() { echo -e "\e[31m[ERROR]\e[0m $1" >&2; }
success() { echo -e "\e[32m[SUCCESS]\e[0m $1"; }

# 检查是否为root权限
check_root() {
    if [ $(id -u) -ne 0 ]; then
        error "### 此脚本必须以root权限运行 !!!"
        exit 1
    fi
}

# 检查系统类型
check_system() {
    if [[ -f /etc/os-release ]] && grep -q "Amazon Linux" /etc/os-release; then
        echo "rhel"
    elif [[ -f /etc/redhat-release ]]; then
        echo "rhel"
    elif [[ -f /etc/debian_version ]]; then
        echo "debian"
    else
        error "不支持的操作系统"
        exit 1
    fi
}

# 判断是否为中国地区
is_china() {
    if command -v curl &> /dev/null; then
        local country=$(curl -sSL --connect-timeout 3 https://ipapi.co/country/ 2>/dev/null | tr -d '\n\r ')
        if [ "$country" = "CN" ]; then
            return 0
        fi
        
        country=$(curl -sSL --connect-timeout 3 https://ipinfo.io/country 2>/dev/null | tr -d '\n\r ')
        if [ "$country" = "CN" ]; then
            return 0
        fi
    fi
    return 1
}

# 安装JDK11
install_jdk11() {
    info "开始安装JDK11..."
    
    if [ -d "$JDK11_DIR" ] && [ -x "$JDK11_DIR/bin/java" ]; then
        success "JDK11已安装在 $JDK11_DIR"
        return 0
    fi
    
    mkdir -p "$JDK11_DIR"
    cd "$JDK11_DIR" || exit 1
    
    # 选择下载源
    if is_china; then
        JDK11_URL="https://repo.huaweicloud.com/java/jdk/11+28/jdk-11_linux-x64_bin.tar.gz"
        info "使用华为云镜像源下载JDK11"
    else
        JDK11_URL="https://github.com/adoptium/temurin11-binaries/releases/download/jdk-11.0.21+9/OpenJDK11U-jdk_x64_linux_hotspot_11.0.21_9.tar.gz"
        info "使用官方GitHub源下载JDK11"
    fi
    
    JDK11_FILE="jdk-11_linux-x64_bin.tar.gz"
    
    if [ ! -f "$JDK11_FILE" ]; then
        info "下载JDK11安装包..."
        if wget --timeout=60 --tries=3 -O "$JDK11_FILE" "$JDK11_URL"; then
            success "JDK11下载成功"
        else
            error "JDK11下载失败"
            return 1
        fi
    fi
    
    info "解压JDK11..."
    tar -xzf "$JDK11_FILE" -C "$JDK11_DIR" --strip-components=1
    
    if [ ! -x "$JDK11_DIR/bin/java" ]; then
        error "JDK11解压失败"
        return 1
    fi
    
    success "JDK11安装完成: $JDK11_DIR"
}

# 安装JDK17
install_jdk17() {
    info "开始安装JDK17..."
    
    if [ -d "$JDK17_DIR" ] && [ -x "$JDK17_DIR/bin/java" ]; then
        success "JDK17已安装在 $JDK17_DIR"
        return 0
    fi
    
    mkdir -p "$JDK17_DIR"
    cd "$JDK17_DIR" || exit 1
    
    # 选择下载源
    if is_china; then
        JDK17_URL="https://repo.huaweicloud.com/openjdk/17/openjdk-17_linux-x64_bin.tar.gz"
        info "使用华为云镜像源下载JDK17"
    else
        JDK17_URL="https://github.com/adoptium/temurin17-binaries/releases/download/jdk-17.0.10+7/OpenJDK17U-jdk_x64_linux_hotspot_17.0.10_7.tar.gz"
        info "使用官方GitHub源下载JDK17"
    fi
    
    JDK17_FILE="openjdk-17_linux-x64_bin.tar.gz"
    
    if [ ! -f "$JDK17_FILE" ]; then
        info "下载JDK17安装包..."
        if wget --timeout=60 --tries=3 -O "$JDK17_FILE" "$JDK17_URL"; then
            success "JDK17下载成功"
        else
            error "JDK17下载失败"
            return 1
        fi
    fi
    
    info "解压JDK17..."
    tar -xzf "$JDK17_FILE" -C "$JDK17_DIR" --strip-components=1
    
    if [ ! -x "$JDK17_DIR/bin/java" ]; then
        error "JDK17解压失败"
        return 1
    fi
    
    success "JDK17安装完成: $JDK17_DIR"
}

# 配置Jenkins使用JDK17启动，系统环境变量保持JDK11
configure_jenkins_startup_jdk() {
    info "配置Jenkins启动使用JDK17，系统环境变量保持JDK11..."
    
    local system_type=$(check_system)
    
    if [[ "$system_type" == "rhel" ]]; then
        # RHEL/CentOS/Amazon Linux系统
        if [[ -f /etc/sysconfig/jenkins ]]; then
            # 备份原配置
            cp /etc/sysconfig/jenkins /etc/sysconfig/jenkins.backup
            
            # 设置Jenkins启动JDK为JDK17
            if grep -q "^JENKINS_JAVA_CMD=" /etc/sysconfig/jenkins; then
                sed -i "s|^JENKINS_JAVA_CMD=.*|JENKINS_JAVA_CMD=\"$JDK17_DIR/bin/java\"|" /etc/sysconfig/jenkins
            else
                echo "JENKINS_JAVA_CMD=\"$JDK17_DIR/bin/java\"" >> /etc/sysconfig/jenkins
            fi
            
            # Jenkins服务专用JAVA_HOME（不影响系统环境变量）
            if grep -q "^JENKINS_JAVA_OPTIONS=" /etc/sysconfig/jenkins; then
                sed -i "s|^JENKINS_JAVA_OPTIONS=.*|JENKINS_JAVA_OPTIONS=\"-Djava.awt.headless=true -Djava.home=$JDK17_DIR\"|" /etc/sysconfig/jenkins
            else
                echo "JENKINS_JAVA_OPTIONS=\"-Djava.awt.headless=true -Djava.home=$JDK17_DIR\"" >> /etc/sysconfig/jenkins
            fi
            
            success "RHEL系统Jenkins启动JDK17配置完成"
        fi
    elif [[ "$system_type" == "debian" ]]; then
        # Debian/Ubuntu系统
        if [[ -f /etc/default/jenkins ]]; then
            # 备份原配置
            cp /etc/default/jenkins /etc/default/jenkins.backup
            
            # 设置Jenkins启动JDK为JDK17
            if grep -q "^JENKINS_JAVA_CMD=" /etc/default/jenkins; then
                sed -i "s|^JENKINS_JAVA_CMD=.*|JENKINS_JAVA_CMD=\"$JDK17_DIR/bin/java\"|" /etc/default/jenkins
            else
                echo "JENKINS_JAVA_CMD=\"$JDK17_DIR/bin/java\"" >> /etc/default/jenkins
            fi
            
            # Jenkins服务专用Java选项
            if grep -q "^JENKINS_JAVA_OPTIONS=" /etc/default/jenkins; then
                sed -i "s|^JENKINS_JAVA_OPTIONS=.*|JENKINS_JAVA_OPTIONS=\"-Djava.awt.headless=true -Djava.home=$JDK17_DIR\"|" /etc/default/jenkins
            else
                echo "JENKINS_JAVA_OPTIONS=\"-Djava.awt.headless=true -Djava.home=$JDK17_DIR\"" >> /etc/default/jenkins
            fi
            
            success "Debian系统Jenkins启动JDK17配置完成"
        fi
    fi
    
    # 修改systemd服务文件（推荐方式）
    if [[ -f /lib/systemd/system/jenkins.service ]] || [[ -f /usr/lib/systemd/system/jenkins.service ]]; then
        local service_file=""
        if [[ -f /lib/systemd/system/jenkins.service ]]; then
            service_file="/lib/systemd/system/jenkins.service"
        else
            service_file="/usr/lib/systemd/system/jenkins.service"
        fi
        
        info "修改systemd服务配置: $service_file"
        cp "$service_file" "$service_file.backup"
        
        # 创建Jenkins服务专用的环境配置
        mkdir -p /etc/systemd/system/jenkins.service.d
        cat > /etc/systemd/system/jenkins.service.d/jdk17.conf << EOF
[Service]
# Jenkins启动专用JDK17配置
Environment="JAVA_HOME=$JDK17_DIR"
Environment="PATH=$JDK17_DIR/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
ExecStart=
ExecStart=$JDK17_DIR/bin/java -Djava.awt.headless=true -jar /usr/share/java/jenkins.war --webroot=/var/cache/jenkins/war --httpPort=8080
EOF
        
        systemctl daemon-reload
        success "systemd服务JDK17配置完成"
    fi
}

# 配置系统环境变量使用JDK11，Jenkins Job也可使用JDK11
configure_system_jdk11() {
    info "配置系统环境变量默认使用JDK11..."
    
    # 配置系统环境变量使用JDK11
    if grep -q "JAVA_HOME=$JDK11_DIR" /etc/profile; then
        info "系统JAVA_HOME已配置为JDK11"
    else
        # 先清理可能存在的其他JAVA_HOME配置
        sed -i '/^export JAVA_HOME=/d' /etc/profile
        sed -i '/^export CLASSPATH=/d' /etc/profile
        sed -i '/^export JRE_HOME=/d' /etc/profile
        
        # 添加JDK11环境变量
        cat >> /etc/profile << EOF

# 系统默认JDK11环境变量
export JAVA_HOME=$JDK11_DIR
export CLASSPATH=\$JAVA_HOME/lib:\$CLASSPATH
export JRE_HOME=\$JAVA_HOME/jre
export PATH=\$JAVA_HOME/bin:\$PATH
EOF
        success "系统环境变量配置为JDK11"
    fi
    
    # 创建软链接指向JDK11
    ln -sf "$JDK11_DIR/bin/java" /usr/bin/java 2>/dev/null || warn "创建java软链接失败，可能需要sudo权限"
    ln -sf "$JDK11_DIR/bin/javac" /usr/bin/javac 2>/dev/null || warn "创建javac软链接失败，可能需要sudo权限"
    
    success "系统默认Java配置完成，指向JDK11"
}

# 配置Jenkins内部JDK工具
configure_jenkins_jdk_tools() {
    info "配置Jenkins内部JDK工具..."
    
    # 创建Jenkins工具配置目录
    mkdir -p "$JENKINS_HOME/tools"
    
    # 创建JDK配置文件
    cat > "$JENKINS_HOME/hudson.model.JDK.xml" << EOF
<?xml version='1.1' encoding='UTF-8'?>
<hudson.model.JDK_-DescriptorImpl>
  <installations>
    <hudson.model.JDK>
      <name>JDK11</name>
      <home>$JDK11_DIR</home>
      <properties/>
    </hudson.model.JDK>
    <hudson.model.JDK>
      <name>JDK17</name>
      <home>$JDK17_DIR</home>
      <properties/>
    </hudson.model.JDK>
  </installations>
</hudson.model.JDK_-DescriptorImpl>
EOF

    # 设置文件权限
    chown -R jenkins:jenkins "$JENKINS_HOME/hudson.model.JDK.xml" 2>/dev/null || chown -R root:root "$JENKINS_HOME/hudson.model.JDK.xml"
    
    success "Jenkins JDK工具配置完成"
    info "JDK11路径: $JDK11_DIR (系统默认)"
    info "JDK17路径: $JDK17_DIR (Jenkins启动专用)"
}

# 创建JDK切换脚本
create_jdk_switch_script() {
    info "创建JDK版本切换脚本..."
    
    cat > /usr/local/bin/jdk-switch << 'EOF'
#!/bin/bash
###
# @Author: Logan.Li
# @Description: JDK版本切换工具
###

JDK11_DIR="/data/jdk-11"
JDK17_DIR="/data/jdk-17"

show_usage() {
    echo "用法: jdk-switch [11|17|list|current]"
    echo "  11      - 切换到JDK11"
    echo "  17      - 切换到JDK17"
    echo "  list    - 显示所有可用JDK版本"
    echo "  current - 显示当前JDK版本"
}

switch_jdk() {
    local version=$1
    local jdk_dir=""
    
    case $version in
        11)
            jdk_dir="$JDK11_DIR"
            ;;
        17)
            jdk_dir="$JDK17_DIR"
            ;;
        *)
            echo "错误: 不支持的JDK版本 $version"
            show_usage
            exit 1
            ;;
    esac
    
    if [ ! -d "$jdk_dir" ]; then
        echo "错误: JDK$version 未安装在 $jdk_dir"
        exit 1
    fi
    
    # 更新环境变量
    export JAVA_HOME="$jdk_dir"
    export PATH="$jdk_dir/bin:$PATH"
    
    echo "已切换到JDK$version: $jdk_dir"
    java -version
}

list_jdk() {
    echo "可用的JDK版本:"
    if [ -d "$JDK11_DIR" ]; then
        echo "  JDK11: $JDK11_DIR"
    fi
    if [ -d "$JDK17_DIR" ]; then
        echo "  JDK17: $JDK17_DIR"
    fi
}

current_jdk() {
    echo "当前JDK版本:"
    if command -v java &> /dev/null; then
        java -version
        echo "JAVA_HOME: ${JAVA_HOME:-未设置}"
    else
        echo "Java未安装或未在PATH中"
    fi
}

case "$1" in
    11|17)
        switch_jdk "$1"
        ;;
    list)
        list_jdk
        ;;
    current)
        current_jdk
        ;;
    *)
        show_usage
        ;;
esac
EOF

    chmod +x /usr/local/bin/jdk-switch
    success "JDK切换脚本创建完成: /usr/local/bin/jdk-switch"
}

# 验证安装
verify_installation() {
    info "验证安装结果..."
    
    echo "========================================="
    echo "JDK安装验证:"
    echo "========================================="
    
    if [ -x "$JDK11_DIR/bin/java" ]; then
        echo "✓ JDK11安装成功: $JDK11_DIR"
        echo "  版本信息:"
        "$JDK11_DIR/bin/java" -version 2>&1 | sed 's/^/    /'
    else
        echo "✗ JDK11安装失败"
    fi
    
    echo ""
    
    if [ -x "$JDK17_DIR/bin/java" ]; then
        echo "✓ JDK17安装成功: $JDK17_DIR"
        echo "  版本信息:"
        "$JDK17_DIR/bin/java" -version 2>&1 | sed 's/^/    /'
    else
        echo "✗ JDK17安装失败"
    fi
    
    echo ""
    echo "========================================="
    echo "配置说明:"
    echo "========================================="
    echo "✓ 系统环境变量默认使用JDK11: $JDK11_DIR"
    echo "✓ Jenkins服务启动使用JDK17: $JDK17_DIR"
    echo "✓ Jenkins Job可选择JDK11或JDK17"
    echo "✓ 命令行和其他应用默认使用JDK11"
    echo ""
    echo "验证配置:"
    echo "  java -version                    # 显示JDK11（系统默认）"
    echo "  systemctl status jenkins         # Jenkins使用JDK17启动"
    echo ""
    echo "JDK切换命令（临时切换当前shell）:"
    echo "  jdk-switch 11      # 切换到JDK11"
    echo "  jdk-switch 17      # 切换到JDK17"
    echo "  jdk-switch list    # 显示所有JDK版本"
    echo "  jdk-switch current # 显示当前JDK版本"
    echo ""
    echo "重启Jenkins服务使配置生效:"
    echo "  systemctl restart jenkins"
    echo "=========================================="
}

# 主函数
main() {
    info "开始Jenkins多JDK版本管理配置..."
    
    check_root
    
    local system_type=$(check_system)
    info "检测到系统类型: $system_type"
    
    # 安装必要命令
    if ! command -v wget &> /dev/null; then
        info "安装wget..."
        if [[ "$system_type" == "rhel" ]]; then
            yum install -y wget
        else
            apt-get update && apt-get install -y wget
        fi
    fi
    
    # 安装JDK11和JDK17
    install_jdk11
    install_jdk17
    
    # 配置系统环境变量使用JDK11
    configure_system_jdk11
    
    # 配置Jenkins启动使用JDK17
    configure_jenkins_startup_jdk
    
    # 配置Jenkins内部JDK工具
    configure_jenkins_jdk_tools
    
    # 创建JDK切换脚本
    create_jdk_switch_script
    
    # 验证安装
    verify_installation
    
    success "Jenkins多JDK版本管理配置完成！"
    
    # 提示重启Jenkins
    warn "请执行以下命令重启Jenkins服务使配置生效:"
    echo "systemctl restart jenkins"
}

# 执行主函数
main "$@"
